package io.gitee.zhucan123.core.infrastructure.util;

import java.util.ArrayList;
import java.util.List;

/**
 * @author guodu
 * @date 2019/11/1
 */
public class NumberUtils {

  /**
   * 将数字转为任意进制，返回各位上的值，调用者自己决定将它位映射到哪些字符
   * @param number 被转换的数字
   * @param scale 进制
   * @return 返回的list高位在前（大端）
   */
  public static List<Integer> scale(long number, int scale) {
    List<Integer> chars = new ArrayList<>();
    while(true) {
      long val = number % scale;
      chars.add(0, (int) val);
      number = number / scale;
      if(number < scale) {
        if(number != 0) {
          chars.add(0, (int)number);
        }
        break;
      }
    }
    return chars;
  }

  /**
   * 将数字转成任意的进制。
   * 例如将 number 转成16进制，则scaleChars传0123456789abedef
   * @param number
   * @param scaleChars 用这个字符序列表示新的进制。
   * @return
   */
  public static String scale(long number, char[] scaleChars) {
    long scale = scaleChars.length;
    StringBuilder sb = new StringBuilder();
    while(true) {
      long val = number % scale;
      sb.insert(0, scaleChars[(int)val]);
      number = number / scale;
      if(number < scale) {
        if(number != 0) {
          sb.insert(0, scaleChars[(int)number]);
        }
        break;
      }
    }
    return sb.toString();
  }

  static int indexOf(char[] scaleChars, char c) {
    for(int i = 0; i < scaleChars.length; i++) {
      if(scaleChars[i] == c) {
        return i;
      }
    }
    return -1;
  }

  /**
   * 将字符串按照指定的进制转回数字
   * @param number
   * @param scaleChars
   * @return
   */
  public static long scale(String number, char[] scaleChars) {
    long scale = scaleChars.length;
    long ret = 0;
    for(int i = 0; i < number.length(); i++) {
      int num = indexOf(scaleChars, number.charAt(i));
      if(num == -1) {
        throw new NumberFormatException();
      }
      ret = ret * scale + num;
    }
    return ret;
  }

}
